const request = require('../../utils/request'); // 引入封装好的请求工具

Page({
  data: {
    formData: {
      phone: "15888888888",
      password: "",
      repassword: "",
      code: "",
      uuid:"",
    },
    loading: false,
    itemStyle: null,
    captchaEnabled: true,
    circles: Array.from({ length: 20 }, (_, index) => index + 1) // 生成1到20的数组
  },
  onShow(){

  },
  onLoad() {
    this.setData({
      circles: Array.from({ length: 20 }, (_, index) => index + 1)
    });
  },
  onChange(e){

    this.setData({
      formData:{
        ...this.data.formData,
        repassword: e.detail
      }
    })

  },
  onChange1(e){

    this.setData({
      formData:{
        ...this.data.formData,
        password: e.detail
      }
    })

  },
  // 表单提交
  handleSubmit(e) {
    const formData = e.detail.value;
    
    // 表单验证
    if (!this.validateForm(formData)) {
      return;
    }
    
    this.setData({ loading: true });
    console.log(this.data.formData, this.data.password, this.data.repassword);
    request.post('/resetPwd',{
      ...this.data.formData
    }).then(
      (res) => {
          console.log(res);
            if (res.code === 200) {
              wx.showToast({
                title: '密码修改成功',
                icon: 'success',
                duration: 2000,
                complete: () => {
                  setTimeout(() => {
                    wx.redirectTo({ url: '/pages/login/login' });
                  }, 2000);
                }
              });
            } else {
              wx.showToast({
                title: res.data.msg || '修改失败',
                icon: 'none'
              });
            }
          },
    )
  },

  // 表单验证
  validateForm(formData) {
    if (!formData.phone || !/^1[3-9]\d{9}$/.test(formData.phone)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
      return false;
    }
    
    if (!formData.password || formData.password.length < 5) {
      wx.showToast({ title: '密码长度至少5位', icon: 'none' });
      return false;
    }
    
    if (formData.password !== formData.repassword) {
      wx.showToast({ title: '两次输入的密码不一致', icon: 'none' });
      return false;
    }
    
    if (this.data.captchaEnabled && !formData.code) {
      wx.showToast({ title: '请输入验证码', icon: 'none' });
      return false;
    }
    
    return true;
  },

  // 获取短信验证码
  getSmsCode() {
    const url = '/yanCode';
    request.get(url)
      .then(response => {
        console.log(response);
        this.setData({
          code: response.data.yanCode,
          formData:{
            ...this.data.formData,
            code: response.data.yanCode,
            uuid: response.data.uuid
          },

        });

      })
      .catch(error => {
        console.error('发送验证码失败:', error);
      });
  },
});